package initialize

import (
	"context"
	"fmt"
	"time"
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/plugin/sysTask/model"
	taskGlobal "github.com/flipped-aurora/gin-vue-admin/server/plugin/sysTask/global"
	"github.com/pkg/errors"
	"go.uber.org/zap"
)

func Gorm(ctx context.Context) {
	err := global.GVA_DB.WithContext(ctx).AutoMigrate(
		new(model.SysTask),
		new(model.SysTaskLog),
	)
	if err != nil {
		err = errors.Wrap(err, "注册表失败!")
		zap.L().Error(fmt.Sprintf("%+v", err))
		return
	}

	// 插入示例数据
	insertSampleData(ctx)
}

// insertSampleData 插入示例任务数据
func insertSampleData(ctx context.Context) {
	// 检查是否已存在相同名称的任务，避免重复插入
	var existingTask model.SysTask
	err := global.GVA_DB.WithContext(ctx).Where("task_name = ?", "ExamplesOne").First(&existingTask).Error
	if err == nil {
		// 任务已存在，跳过插入
		zap.L().Info("示例任务已存在，跳过插入", zap.String("taskName", "ExamplesOne"))
		return
	}

	// 创建示例任务数据
	// 对应数据: '1','2025-10-30 16:34:30.911','2025-10-30 16:34:52.077',NULL,'ExamplesOne','demo','@every 1s','ExamplesOne','',NULL,'0','1','0','0','internalFuncTask','ExamplesOne','99'
	createdAt, _ := time.Parse("2006-01-02 15:04:05.000", "2025-10-30 16:34:30.911")
	updatedAt, _ := time.Parse("2006-01-02 15:04:05.000", "2025-10-30 16:34:52.077")
	
	// 创建指针类型的变量
	args := ""
	timeout := int64(0)
	multi := int8(1)
	retryTimes := int8(0)
	retryInterval := int64(0)
	tag := "internalFuncTask"
	remark := "ExamplesOne"
	status := taskGlobal.Disabled

	sampleTask := model.SysTask{
		CreatedAt:      createdAt,
		UpdatedAt:      updatedAt,
		TaskName:       "ExamplesOne",
		TaskGroup:      "demo",
		CronExpression: "@every 1s",
		InvokeTarget:   "ExamplesOne",
		Args:           &args,
		HttpMethod:     nil, // NULL
		Timeout:        &timeout,
		Multi:          &multi,
		RetryTimes:     &retryTimes,
		RetryInterval:  &retryInterval,
		Tag:            &tag,
		Remark:         &remark,
		Status:         &status,
	}

	// 插入数据
	err = global.GVA_DB.WithContext(ctx).Create(&sampleTask).Error
	if err != nil {
		zap.L().Error("插入示例任务数据失败", zap.Error(err))
	} else {
		zap.L().Info("示例任务数据插入成功", zap.Uint("taskId", uint(sampleTask.ID)), zap.String("taskName", sampleTask.TaskName))
	}
}
	